package org.gitman.filmBase.model;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Collection;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.gitman.filmBase.model.database.IFacade;
import org.gitman.filmBase.model.database.MockFacade;
import org.gitman.filmBase.view.View;

public class Model {
	
	private View view;
	private Collection<Film> films;
	private Collection<Person> persons;
	private IFacade facade;
	private String driver = "org.apache.derby.jdbc.EmbeddedDriver";
	private static Logger logger = Logger.getLogger(Model.class);
    private String protocol = "jdbc:derby:";
    private String dbName = "filmdb";
    private String user = "filmbase";
    private String password = "filmbase";
	
	public Model(){
		loadDriver();
		testAndCreateFilmDB();
		facade = new MockFacade();
	}
	private void testAndCreateFilmDB() {
		Connection conn = null;
		Properties props = new Properties(); 
        props.put("user", user);
        props.put("password", password);
    	try {
    		conn = DriverManager.getConnection(protocol + dbName + ";create=false", props);
			logger.info("DB: Connected to existing database " + dbName);
		} catch (SQLException e) {
			logger.info("can't conect to DB, creating new");
		} finally {
			if (conn == null) {
					try {
						conn = DriverManager.getConnection(protocol + dbName + ";create=true", props);
						logger.info("DB: Created database " + dbName);
						createTables(conn);
					} catch (SQLException e) {
						logger.error(e);
					}
			}
		}
	}
	private void createTables(Connection conn) {
		// TODO Auto-generated method stub
		
	}
	private void loadDriver() {
        try {
            Class.forName(driver).newInstance();
            logger.info("DB: Loaded the appropriate driver");
        } catch (ClassNotFoundException cnfe) {
        	logger.error("DB: Unable to load the JDBC driver " + driver);
        	logger.error("DB: Please check your CLASSPATH.");
        } catch (InstantiationException ie) {
        	logger.error("DB: Unable to instantiate the JDBC driver " + driver);
        } catch (IllegalAccessException iae) {
        	logger.error("DB: Not allowed to access the JDBC driver " + driver);
        }
    }
	public View getView() {
		return view;
	}
	public void setView(View view) {
		this.view = view;
	}
	public Collection<Film> getAllFilms(){
		return films;
	}
	public Collection<Person> getAllPesons(){
		return persons;
	}
	public void load(){
		films = facade.getAllFilms();
		persons = facade.getAllPersons();
	}
	public void save(){
		
	}
}
